"""
依赖模块：
    wordcloud
"""
import wordcloud
import requests
import bs4
import json


def createCiCloud(text, noText):
    """
        创建词云
    """
    # scale参数决定清晰度
    wc = wordcloud.WordCloud(font_path="C:\\Windows\\Fonts\\simhei.ttf", stopwords=noText, background_color="white",
                             scale=25)
    wc.generate(text)
    wc.to_file("词云.png")
    image = wc.to_image()
    image.show()


def open_url(url):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }
    res = requests.get(url, headers=headers)
    return res


def getTopList(url):
    """
        获取排行榜
        :return: 返回一个字典，name: 歌曲名称，artists: 歌曲作者
    """
    TopList = []
    res = open_url("https://music.163.com/discover/toplist")
    html = bs4.BeautifulSoup(res.text, "html.parser")
    topSongJson = json.loads(html.find_all(
        "textarea", id="song-list-pre-data")[0].get_text())
    for item in topSongJson:
        songInfo = {}
        songInfo["id"] = item["id"]
        songInfo["name"] = item["name"]
        songInfo["artists"] = item["artists"][0]["name"]
        songInfo["url"] = "https://music.163.com/#/song?id=" + str(item["id"])
        TopList.append(songInfo)
    return TopList


def main():
    print("正在获取热门歌手")
    TopList = getTopList("https://music.163.com/discover/toplist")
    text = ""
    for item in TopList:
        text = text + " " + item['artists']
    with open('歌手词库.txt', 'w', encoding='utf8') as file:
        file.write(text)
    print("热门歌手获取完成")
    # with open(r"词云.txt", encoding="utf-8") as file:
    #     text = file.read()
    # with open(r"黑名单.txt", encoding="utf-8") as file:
    #     blackList = file.read()
    createCiCloud(text, "")


if __name__ == '__main__':
    main()
